package edu.ec.java02.group02.controller;

import edu.ec.java02.group02.domain.Cart;
import edu.ec.java02.group02.domain.UserInfo;
import edu.ec.java02.group02.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/front")
public class CartController {

    @Autowired
    CartService cartService;

    @RequestMapping("add")
    public void addCart(HttpServletRequest request,HttpServletResponse response){

        Integer productId = Integer.parseInt(request.getParameter("productId"));
        Integer num = Integer.parseInt(request.getParameter("number"));
        UserInfo user = (UserInfo)request.getSession().getAttribute("login");
        Cart cart = new Cart();
        cart.setProductId(productId);
        cart.setUserId(user.getUserId());
        cart.setProductNumber(num);//默认添加商品的数量为1
        PrintWriter out= null;
        try {
            out = response.getWriter();
            if(cartService.findProductById(user.getUserId(),productId)){
                if(cartService.updateCart(cart))
                    out.write("ok");
                else
                    out.write("no");
            }else{
                if (cartService.addCart(cart))
                    out.write("ok");
                else
                    out.write("no");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("show")
    public String showCart(HttpServletRequest request){

        UserInfo user =(UserInfo)request.getSession().getAttribute("login");

        request.setAttribute("ls",cartService.findCartInfoById(user.getUserId()));

        return "/front/protected/shopcart";
    }

    @RequestMapping("del")
    public void delProduct(HttpServletRequest request,HttpServletResponse response){

       // Integer productId = Integer.parseInt(request.getParameter("productId"));
        String[]  productIds = request.getParameter("productId").split(";");

//        UserInfo user = (UserInfo)request.getSession().getAttribute("login");
//        Cart cart = new Cart();
//        cart.setProductId(productId);
//        cart.setUserId(user.getUserId());

        UserInfo user = (UserInfo)request.getSession().getAttribute("login");

        PrintWriter out= null;
        try {
            out = response.getWriter();
            if(cartService.delProduct(user.getUserId(),productIds))
                out.write("ok");
            else
                out.write("no");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
